package com.example.deepai.service;

import com.example.deepai.model.UIElement;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.List;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.*;

@Slf4j
@Service
@RequiredArgsConstructor
public class UIAnalysisService {
    private final OpenCVUIDetectionService opencvService;
    private final QwenVisionService qwenService;
    private final VectorDBService vectorDBService;

    public void analyzeAndStoreUI(String imagePath, String base64Image) {
        try {
            // 1. 使用 OpenCV 检测 UI 元素
            List<UIElement> elements = opencvService.detectUIElements(imagePath);
            
            // 2. 使用通义千问进行语义分析
            String aiAnalysis = qwenService.analyzeImage(base64Image, 
                "Please analyze these UI elements and describe their functions and relationships.");
            
            // 3. 存储到 Milvus 向量数据库
            for (UIElement element : elements) {
                // 这里需要实现将 AI 分析结果转换为特征向量的逻辑
                float[] featureVector = convertToFeatureVector(element, aiAnalysis);
                vectorDBService.storeUIComponent(element, featureVector);
            }
            
            log.info("Successfully analyzed and stored {} UI elements", elements.size());
            
        } catch (Exception e) {
            log.error("Failed to analyze and store UI elements", e);
            throw new RuntimeException("UI analysis failed", e);
        }
    }
    
    private float[] convertToFeatureVector(UIElement element, String aiAnalysis) {
        float[] vector = new float[512];
        try {
            // 1. 解析 AI 分析结果（假设返回的是 JSON 格式）
            ObjectMapper mapper = new ObjectMapper();
            JsonNode analysisJson = mapper.readTree(aiAnalysis);
            
            // 2. 提取元素特征
            // 位置特征 (归一化到 0-1 范围)
            vector[0] = normalizeCoordinate(element.getX());
            vector[1] = normalizeCoordinate(element.getY());
            vector[2] = normalizeCoordinate(element.getWidth());
            vector[3] = normalizeCoordinate(element.getHeight());
            
            // 3. 元素类型编码 (one-hot encoding)
            String elementType = element.getType().toLowerCase();
            int typeOffset = 4;
            vector[typeOffset + getTypeIndex(elementType)] = 1.0f;
            
            // 4. 从 AI 分析中提取语义特征
            if (analysisJson.has("elements")) {
                for (JsonNode elementNode : analysisJson.get("elements")) {
                    if (matchesElement(elementNode, element)) {
                        // 提取描述并转换为向量
                        String description = elementNode.get("description").asText();
                        float[] descriptionVector = textToVector(description);
                        System.arraycopy(descriptionVector, 0, vector, 20, descriptionVector.length);
                        break;
                    }
                }
            }
            
            // 5. 归一化最终向量
            normalizeVector(vector);
            
            // 6. 转换为 List<Float>
            List<Float> vectorList = new ArrayList<>(vector.length);
            for (float v : vector) {
                vectorList.add(v);
            }
            
            return vector;
            
        } catch (Exception e) {
            log.error("Error converting to feature vector", e);
            // 在转换失败时返回随机向量
            Random random = new Random();
            float[] randomVector = new float[512];
            for (int i = 0; i < randomVector.length; i++) {
                randomVector[i] = random.nextFloat();
            }
            normalizeVector(randomVector);
            return randomVector;
        }
    }
    
    private float normalizeCoordinate(int value) {
        return value / 1000.0f; // 假设屏幕尺寸最大为 1000
    }
    
    private int getTypeIndex(String type) {
        switch (type) {
            case "button": return 0;
            case "input": return 1;
            case "text": return 2;
            case "image": return 3;
            default: return 4;
        }
    }
    
    private boolean matchesElement(JsonNode node, UIElement element) {
        // 基于位置和类型匹配元素
        return node.has("type") && 
               node.get("type").asText().equalsIgnoreCase(element.getType());
    }
    
    private float[] textToVector(String text) {
        float[] vector = new float[492]; // 512 - 20 (预留给其他特征)
        // 简单的词袋模型实现
        Set<String> words = new HashSet<>(Arrays.asList(text.toLowerCase().split("\\s+")));
        for (int i = 0; i < vector.length && i < words.size(); i++) {
            vector[i] = 1.0f;
        }
        return vector;
    }
    
    private void normalizeVector(float[] vector) {
        float sum = 0;
        for (float v : vector) {
            sum += v * v;
        }
        float norm = (float) Math.sqrt(sum);
        if (norm > 0) {
            for (int i = 0; i < vector.length; i++) {
                vector[i] /= norm;
            }
        }
    }
}